package tianrun.ziguan.api.calculate.config.service.ge.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import tianrun.ziguan.api.calculate.config.constant.StringPools;
import tianrun.ziguan.api.calculate.config.dao.ge.TGeTableConfigMapper;
import tianrun.ziguan.api.calculate.config.entity.ge.TGeTableConfig;
import tianrun.ziguan.api.calculate.config.service.ge.TGeTableConfigService;
import tianrun.ziguan.api.calculate.config.utils.CollectionUtil;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class TGeTableConfigServiceImpl extends ServiceImpl<TGeTableConfigMapper, TGeTableConfig> implements TGeTableConfigService {
    private final Cache<String, List<TGeTableConfig>> cache = CacheBuilder.newBuilder().expireAfterWrite(24 * 60, TimeUnit.MINUTES).build();
    private final Cache<String, TGeTableConfig> primaryCache = CacheBuilder.newBuilder().build();

    @Override
    public List<TGeTableConfig> listByTableName(String tableName) {
        try {
            return cache.get(tableName, () -> list(Wrappers.<TGeTableConfig>lambdaQuery().eq(TGeTableConfig::getTableName, tableName)));
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, TGeTableConfig> mapByTableName(String tableName) {
        return CollectionUtil.toMap(listByTableName(tableName), TGeTableConfig::getColumnName);
    }

    @Override
    public Map<String, TGeTableConfig.Type> typeConfigs(String tableName) {
        return CollectionUtil.toMap(listByTableName(tableName), TGeTableConfig::getColumnName, TGeTableConfig::getType);
    }

    @Override
    public List<String> columns(String tableName) {
        return CollectionUtil.toList(listByTableName(tableName), TGeTableConfig::getColumnName);
    }

    @Override
    public String primaryKey(String tableName) {
        try {
            TGeTableConfig config = primaryCache.get(tableName, () -> baseMapper.selectOne(Wrappers.<TGeTableConfig>lambdaQuery().select(TGeTableConfig::getColumnName).eq(TGeTableConfig::getTableName, tableName).eq(TGeTableConfig::getPrimaryKey, true).last(StringPools.LAST_SQL)));
            Assert.notNull(config, tableName + "无相关配置！");
            return config.getColumnName();
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
